// 柱状图叠加
import React, {useState, useEffect} from 'react';
import {Table, Pagination, Progress} from 'antd';
import {parsePercent, numberHandle, safeMultiple} from '~/utils/number';
import CommonEchart from '~/page/FineBi/common/CommonEchart';
import {transformTableData} from '~/page/FineBi/utils/convert';
import {getColumnValue} from '../utils';
import withPannel from './withPannel';

const getLeftAxis = isSpecial => {
    if (isSpecial) {
        return [
            {
                yAxisIndex: 0,
                name: '老学员可续人数占比',
                stack: '总量',
            },
            {
                yAxisIndex: 0,
                name: '新学员可续人数占比',
                stack: '总量',
            }
        ];
    }
    return [
        {
            yAxisIndex: 0,
            name: '老学员可续人数',
            stack: '总量',
        },
        {
            yAxisIndex: 0,
            name: '新学员可续人数',
            stack: '总量',
        }
    ];
};

const tooltipCallback = params => {
    let resultName = '';
    const tooltipList = params.map(chartItem => {
        const {seriesType, seriesName, name, value, data: {num}, marker} = chartItem;
        let result;
        resultName = name;

        if (num) {
            result = `<br/>${marker} ${seriesName} ${Number(num)} (${parsePercent(value, 2)})`;
        } else if (seriesType === 'bar') {
            result = `<br/>${marker} ${seriesName} ${Number(value)}`;
        } else {
            result = `<br/>${marker} ${seriesName} ${parsePercent(value, 2)}`;
        }

        return result;
    });

    return resultName + tooltipList.join('');
};


// 数据上的标签
const labelFormatter = (params = {}) => {
    const {
        data: {proportion = 0} = {},
        seriesType,
        value
    } = params;

    if (seriesType === 'bar') {
        return value ? numberHandle(value, 2) : '';
    }

    return value ? parsePercent(value, 2) : '';
};

const extendOptions = isSpecial => ({
    tooltip: {
        trigger: 'axis',
        formatter: tooltipCallback
    },
    legend: {
        left: 'left',
    },
    xAxis: {
        common: {
            axisLabel: {
                // rotate: 30
            }
        }
    },
    yAxis: {
        // 多个轴的格式化
        newYAxis: [
            {
                type: 'value',
                axisLabel: {
                    formatter(value) {
                        return isSpecial ? `${safeMultiple(value, 100)}%` : numberHandle(value, 0);
                    }
                }
            },
            {
                type: 'value',
                axisLabel: {formatter: value => `${safeMultiple(value, 100)}%`}
            }
        ],
        common: {
            splitLine: {show: false},
        }
    },
    grid: {
        left: 40,
        right: '3%',
        bottom: 20,
        containLabel: true
    },
    series: {
        newYAxis: [
            ...getLeftAxis(isSpecial),
            // 左侧
            // {
            //     yAxisIndex: 0,
            //     name: '老学员可续人数',
            //     stack: '总量',
            // },
            // {
            //     yAxisIndex: 0,
            //     name: '新学员可续人数',
            //     stack: '总量',
            // },
            // 右侧轴
            {
                yAxisIndex: 1,
                name: '老学员综合续班率',
            },
            {
                yAxisIndex: 1,
                name: '新学员综合续班率',
            },
        ],
        common: {
            // stack: '总量',
            barMaxWidth: 30,
            barGap: '100%',
            barCategoryGap: '50%',
            // label: {show: true, position: 'inside', formatter: labelFormatter}
        }
    }
});


const StructureBarChart = props => {
    const {dataSource, pager, children, fetchData, onPagerChange} = props;
    const [tableInfo, echartInfo] = children || [];
    // fetchData 表示特殊接口。比常规接口多了一个字段：数据占比
    const isSpecial = !!fetchData;

    const [data, setData] = useState([]);
    const [columns, setColumns] = useState([]);
    const {unitId: tableUnitId, columnsConfig, notTransformTable, pagerVisible, customRender, fixedIdxEnd} = tableInfo;
    const echartUnitId = echartInfo?.unitId;
    const echartData = dataSource?.[echartUnitId] || {};


    useEffect(() => {
        const columnList = dataSource?.[tableUnitId]?.columnList || [];
        const value = dataSource?.[tableUnitId]?.value || [];
        const [newColumnList, newValue] = notTransformTable
            ? [columnList, value]
            : transformTableData(columnList, value);
        const newColumns = (columnsConfig || newColumnList)?.map((item, index) => ({
            title: item.name,
            width: 100,
            fixed: fixedIdxEnd && index < fixedIdxEnd && 'left',
            render(row) {
                const originValue = row[item.name];

                if (customRender) {
                    return getColumnValue(originValue, item.name);
                }

                if (isNaN(originValue)) {
                    return originValue;
                }

                return Number(originValue).toFixed(0);
            }
        }));

        setColumns(newColumns);
        setData(newValue);
    }, [dataSource]);

    return (
        <>
            <Table
                dataSource={data}
                columns={columns}
                pagination={false}
                size="small"
                scroll={{x: 'max-content'}}
                // {...tableProps}
            />
            {pagerVisible && (
                <Pagination
                    className="dtPager"
                    size="small"
                    total={pager.count}
                    current={pager.pageNum}
                    pageSize={pager.pageSize}
                    onChange={onPagerChange}
                    showSizeChanger
                    pageSizeOptions={['10', '20', '50', '100']}
                />
            )}
            {echartInfo && (
                <>
                    <br />
                    <CommonEchart
                        {...props}
                        id={echartUnitId}
                        extendEchartsOptions={extendOptions(isSpecial)}
                        dataSource={echartData}
                    />
                </>

            )}
        </>
    );
};

export default withPannel(StructureBarChart, 'isTable');
